<template>
  <a-row :class="['p-4', `${prefixCls}--box`]" type="flex" :gutter="10" style="max-height: 800px">
    <a-col :xl="6" :lg="24" :md="24" style="margin-bottom: 10px">
      <DepartLeftTree ref="leftTree" @select="onTreeSelect" />
    </a-col>
    <a-col :xl="18" :lg="24" :md="24" style="margin-bottom: 10px">
      <a-card :bordered="false" class="j-print-demo" :title="orgName">
        <div style="display: flex;" v-show="orgName == '请选择公司' ? false : true">
          <span style="margin-left: 2%;">企业级别：{{ memo }}</span><span style="margin-left: 2%;">核定员额数：100</span>
          <span style="margin-left: 2%;">实有员额数：22</span><span style="margin-left: 2%;">剩余员额数量：3</span>
          <span style="margin-left: 2%;">核定领导职数：{{ position }}</span>
          <span style="margin-left: 2%;">核定内设机构数量：{{ internalInstitutions }} </span>
        </div>
      </a-card>
      <a-card :bordered="false" class="j-print-demo" style="margin-top: 2%;" v-show="orgName == '请选择公司' ? false : true">
        <div style="height: 100%;" class="address-book">
          <!--引用表格-->
          <BasicTable @register="registerTable">
            <template #post="{ text }">
              {{
                (text || '')
                  .split(',')
                  .map((t) => (positionInfo[t] ? positionInfo[t] : t))
                  .join(',')
              }}
            </template>
            <!--操作栏:dropDownActions="getDropDownAction(record)"-->
            <template #action="{ record }">
              <TableAction :actions="getTableAction(record)" />
            </template>
          </BasicTable>
          <!--用户抽屉-->
          <UserDrawer @register="registerDrawer" @success="handleSuccess" />
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
import UserDrawer from './UserDrawer.vue';
import { provide, ref, unref } from 'vue';
import { useDesign } from '/@/hooks/web/useDesign';
import DepartLeftTree from './components/DepartLeftTree.vue';
import { BasicTable, ActionItem, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, searchFormSchema } from './address.data';
import { list, positionList } from './address.api';
import { useDrawer } from '/@/components/Drawer';
import { getDepartName } from './getpData.api';

//内设机构数internalInstitutions
const internalInstitutions = ref('');
//部门员额数member
const member = ref('');
//副职deputyPosition
const deputyPosition = ref('');
//分子公司数subsidiary
const subsidiary = ref('');
//chiefPosition正职
const chiefPosition = ref('');
//chiefPosition正职
const position = ref('');

const chiefPositionDeputyPositionStr = ref('');

//级别备注
const memo = ref('');







//注册drawer
const [registerDrawer, { openDrawer }] = useDrawer();
/**
  * 操作栏
  */
function getTableAction(record): ActionItem[] {
  //console.log('recordrecordrecord',record); 
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      // ifShow: () => hasPermission('system:user:edit'),
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
  ];
}

/**
  * 编辑事件
  */
async function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: true,
    tenantSaas: false,
  });
}

/**
 * 下拉操作栏
 */
function getDropDownAction(record): ActionItem[] {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    // {
    //   label: '代理人',
    //   onClick: handleAgentSettings.bind(null, record.username),
    // },
  ];
}

/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}


/**
 * 详情
 */
async function handleDetail(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: false,
    tenantSaas: false,
  });
}






















const { prefixCls } = useDesign('address-list');
provide('prefixCls', prefixCls);

// 给子组件定义一个ref变量
const leftTree = ref();

// 当前选中的部门code
const orgCode = ref('');
const positionInfo = ref({});
const orgName = ref('请选择公司');
// 列表页面公共参数、方法
const { tableContext } = useListPage({
  tableProps: {
    api: list,
    columns,
    //update-begin---author:wangshuai ---date:20220629  for：[VUEN-1485]进入系统管理--通讯录页面后，网页命令行报错------------
    rowKey: 'userId',
    //update-end---author:wangshuai ---date:20220629  for：[VUEN-1485]进入系统管理--通讯录页面后，网页命令行报错--------------
    showIndexColumn: true,
    formConfig: {
      schemas: searchFormSchema,
    },
    canResize: false,
    actionColumn: {
      width: 120,
    },
    showTableSetting: false,
    // 请求之前对参数做处理
    beforeFetch(params) {
      params.orgCode = orgCode.value;
    },
  },
});
//注册table数据
const [registerTable, { reload }] = tableContext;


function convertNumberToChinese(num: string): string {
  const numMap: { [key: string]: string } = {
    "1": "一",
    "2": "二",
    "3": "三",
    "4": "四",
    "5": "五",
    "6": "六",
    "7": "七",
    "8": "八",
    "9": "九",
    "0": "零"
  };

  return num.split('').map(digit => numMap[digit]).join('');
}
function convertToText(input: string): string {
  const match = input.match(/^(\d+)-(\d+)$/);

  if (match) {
    const [, num1, num2] = match;
    const num1Chinese = convertNumberToChinese(num1);
    const num2Chinese = convertNumberToChinese(num2);

    return `${num1Chinese}正${num2Chinese}副`;
  }

  return input; // 如果格式不符合预期，返回原始输入
}
// 左侧树选择后触发
// //内设机构数internalInstitutions
// const internalInstitutions = ref('');
// //部门员额数member
// const member = ref('');
// //副职deputyPosition
// const deputyPosition = ref('');
// //分子公司数subsidiary
// const subsidiary = ref('');
// //chiefPosition正职
// const chiefPosition = ref('');
async function onTreeSelect(data) {
  if (data.chiefPositionDeputyPositionStr == '0-0') {
    chiefPositionDeputyPositionStr.value = '未设置'
  } else {
    chiefPositionDeputyPositionStr.value = convertToText(data.chiefPositionDeputyPositionStr)
  }
  if (data.memo == null) {
    memo.value = '未设置'
  } else {
    memo.value = data.memo
  }
  internalInstitutions.value = data.internalInstitutions
  console.log('datadatadatadatadatadatadatadatadatadatadata', data)
  orgName.value = data.departName
  orgCode.value = data.orgCode;
  //getDepartName
  const getDepart = await getDepartName(data.orgCode);
  console.log('getDepartgetDepartgetDepartgetDepartgetDepart', getDepart)
  reload();
}

// 查询职务信息
async function queryPositionInfo() {
  const result = await positionList({ pageSize: 99999 });
  if (result) {
    let obj = {};
    result.records.forEach((position) => {
      obj[position['id']] = position['name'];
    });
    positionInfo.value = obj;
  }
}
queryPositionInfo();
</script>

<style lang="less">
@import './index.less';

.j-print-demo .ant-card-body {
  margin: 0;
  border: 0 solid black;
  min-width: 800px;
  color: #000000 !important;
}
</style>
